package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    EditText et1,et2;
    SharedPreferences sp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et1=findViewById(R.id.et1);
        et2=findViewById(R.id.et2);
        sp=getPreferences(Activity.MODE_PRIVATE);
        String username=sp.getString("username","");
        String password=sp.getString("password","");
        et1.setText(username);
        et2.setText(password);
        Button btn1=findViewById(R.id.btn1);
        btn1.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                String s1=et1.getText().toString();
                String s2=et2.getText().toString();
                Toast.makeText(getApplicationContext(),"输入的用户名为"+s1+"，输入的密码为"+s2,Toast.LENGTH_LONG).show();
            }
        });
        Button btn2=findViewById(R.id.btn2);
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                et1.setText("");
                et2.setText("");
                Toast.makeText(getApplicationContext(),"取消登录",Toast.LENGTH_SHORT).show();
            }
        });
        CheckBox cb=findViewById(R.id.checkBox);
        cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(b){
                    Toast.makeText(MainActivity.this,"已保存登录信息",Toast.LENGTH_LONG).show();
                    sp.edit().putString("username",et1.getText().toString())
                            .putString("password",et2.getText().toString())
                            .commit();
                }else{
                    Toast.makeText(MainActivity.this,"不保存登录信息",Toast.LENGTH_LONG).show();
                    sp.edit().putString("username",null)
                            .putString("password",null)
                            .commit();
                }
            }
        });
    }
}